package com.imau.listener;

import javax.servlet.ServletContext;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

/**
 * 监听session创建
 */
@WebListener
public class OnliCountHttpSessiontListener implements HttpSessionListener {

    public void sessionCreated(HttpSessionEvent se)
    {

        //获取session
        HttpSession session = se.getSession();
        System.out.println("上线了="+session.getId());
        //获取ServletContext对象
        ServletContext servletContext = session.getServletContext();
        //获取count属性值
        Integer count = (Integer) servletContext.getAttribute("count");
          ++count;
        servletContext.setAttribute("count",count);
        System.out.println("在线人数="+count);
    }

    //session失效 ：过期
    public void sessionDestroyed(HttpSessionEvent se)
    {
        //获取session
        HttpSession session = se.getSession();
        System.out.println("下线了"+session.getId());
        //获取ServletContext对象
        ServletContext servletContext = session.getServletContext();
        //获取count属性值
        Integer count = (Integer) servletContext.getAttribute("count");
        --count;
        servletContext.setAttribute("count",count);
        System.out.println("在线人数="+count);
    }
}
